package com.findMoneyGame.pages.game.controllers {
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFieldAutoSize;

	import com.findMoneyGame.pages.game.GameLevelPage;
	import com.findMoneyGame.pages.game.controllers.Controller;
	import com.findMoneyGame.tools.TextFormatProvider;

	public class LoupeController extends Controller {
		private function get loupeButton () { return _gameLevelPage.loupeButton; }

		public function LoupeController (gameLevelPage : GameLevelPage) {
			super(gameLevelPage);
			loupeButton.price = gameLevel.data.loupePrice;
			loupeButton.addEventListener(MouseEvent.CLICK, loupeButtonClick);
		}

		private function loupeButtonClick (e : Event) {
			if (gameImage.loupeEnabled)
				return;
			if (user.moneyCount < gameLevel.data.loupePrice) {
				_gameLevelPage.dispatchEvent(new Event(GameLevelPage.NEED_MORE_MONEY));
				return;
			}

			user.takeMoney(gameLevel.data.loupePrice);
			gameImage.enableLoupe();

			var text = initTextField(gameLevel.data.loupeTime + 'c');
			loupeButton.addChild(text);

			var loupeTimer = new Timer(1000, gameLevel.data.loupeTime);
			loupeTimer.addEventListener(TimerEvent.TIMER, 
				function (e : Event) {
					text.text = (gameLevel.data.loupeTime - loupeTimer.currentCount) + 'с';
				}
			);
			loupeTimer.addEventListener(TimerEvent.TIMER_COMPLETE, 
				function (e : Event) {
					trace('GameLevelPage.loupeButtonClick() убираем лупу');
					loupeButton.removeChild(text);
					gameImage.disableLoupe();
				}
			);
			loupeTimer.start();
		}
		private function initTextField (s : String) : TextField {
			var format = TextFormatProvider.getFormat(30, 0xFFFFFF);
			var text = new TextField();
			text.x = 10;
			text.y = 6;
			text.width = 70;
			text.height = 70;
			text.autoSize = TextFieldAutoSize.LEFT;
			text.selectable = false;
			text.setTextFormat(format);
			text.defaultTextFormat = format;
			text.text = s;
			return text;
		}
	}
}